<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Library\Yunxin;
use App\Models\Currency;
use App\Models\EmailSms;
use App\Models\LoginLog;
use App\Models\Message;
use App\Models\PhoneSms;
use App\Models\Property;
use App\Models\User;
use App\Models\Send;
use App\Traits\YunXinTrait;
use DB;
use Exception;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    use YunXinTrait;

    /**
     * 登录.
     *
     * @author hxq
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function log_in(Request $request)
    {
        //账号
        $account = $request->get('account');
        //密码
        $password = $request->get('password');
        //验证参数
        if (empty($account) || empty($password)) {
            return respF(1003);
        }
        //判断是手机还是邮箱
        if (isPhone($account)) {
            $user = User::where('phone', $account)->first();
        } else if(isEmail($account)) {
            $user = User::where('email', $account)->first();
        } else {
            return respF(2011);
        }
        if (!$user) {
            //账号未注册
            return respF(4004);
        }
        //没有用户
        if ($user->password != md5($password)) {
            //账号或密码错误
            return respF(2010);
        }
        //限制商家身份登录
        /*if ($user->type == 2) {
            //限制商家登录APP
            return respF(4003);
        }*/
        //客户端IP

        $ip = $request->getClientIp();
        //根据IP获取地理信息
        //$lookup = GetIpLookup($ip);
        $address = '';
        //组装地址
//        if ($lookup)
//            $address = $lookup['country'].$lookup['province'].$lookup['city'];
        //写入登录历史
        LoginLog::create([
            'uid' => $user->id,
            'client' => 'phone',
            'ip' => $ip,
            'address' => $address,
            'status' => 1,
        ]);
        //更新登录信息 2018-5-5
        $map['token'] = md5(time());
        $map['islogin'] = 1;
        $token = substr($user->token, 0, 6);

        $user_updata = $user->update($map);

        if (!$user_updata) {
            //更新出错
            return respF(3023);
        }
        //end 2018-5-5
        //调用云信更新信息
        $model = new Yunxin\Yunxin();
        $name = $user->nickname;
        $id = $user->id;
        $img = config('alioss.host').'/'.$user->headimg;
        $model->change_yx($id, $name, $img, $map['token']);
        //推送
        if ($user->islogin == 1) {
            $key = $id.$token;
            (new Send())->send(1, $key, '', '', '-1');
        }
        $data['uid'] = $user->id;
        $data['account'] = $user->account;
        $data['nickname'] = $user->nickname;
        $data['email'] = $user->email;
        $data['phone'] = $user->phone;
        $data['headimg'] = config('alioss.host').$user->headimg;
        $data['real_status'] = $user->real_status;
        $data['type'] = $user->type;
        $data['is_pay_pass'] = empty($user->pay_pass) ? 0 : 1;
        $data['alipay'] = $user->user_alipay;
        $data['wechat'] = $user->user_wechat;
        $data['bind_pay'] = 0;
        if ($user->user_alipay || $user->user_wechat) {
            $data['bind_pay'] = 1;
        }
        $autonym = $user->autonym()->select('name', 'indentity_card', 'back_card', 'front_card', 'status')->first();
        if ($autonym) {
            $data['front_card'] = $autonym->front_card ? config('alioss.host').'/'.$autonym->front_card : '';
            $data['back_card'] = $autonym->back_card ? config('alioss.host').'/'.$autonym->back_card : '';
            $data['hand_card'] = $autonym->hand_card ? config('alioss.host').'/'.$autonym->hand_card : '';
            $data['name'] = $autonym->name;
            $data['indentity_card'] = $autonym->indentity_card;
            $data['status'] = $autonym->status;
        }
        $data['token'] = $user->token;
        $data['islogin'] = $user->islogin;
        return response()->json(['status' => 1, 'msg' => '登录成功', 'data' => $data]);
    }

    /**
     * 注册.
     *
     * @author hxq
     *
     * @param Request $request [description]
     *
     * @return \Illuminate\Http\JsonResponse [type] [description]
     */
    public function sign_in(Request $request)
    {
        try {
            $data = [];
            $account = $request->get('account');
            $password = $request->get('password');
            $code = $request->get('code');

            if (empty($account) || empty($password) || empty($code)) {
                throw new Exception(1003);
            }
            //判断是邮箱还是手机号
            $email = $phone = $user = $check = null;

            if (isPhone($account)) {
                $phone = $account;
                $user = User::where(['phone' => $account])->first();
                $check = PhoneSms::where(['phone' => $account, 'type' => 2])
                    ->orderBy('created_at', 'desc')->first();
            } elseif (isEmail($account)) {
                $email = $account;
                $user = User::where(['email' => $account])->first();
                $check = EmailSms::where(['email' => $account, 'type' => 2])
                    ->orderBy('created_at', 'desc')->first();
            } else {
                throw new Exception(2011);
            }

            if ($user) {
                //账号已注册
                throw new Exception(2012);
            }
            /*if (!$check) {
            throw new Exception('请获取验证码');
            }
            if ($check->expire_time < time()) {
            throw new Exception('验证码已过期');
            }
            if ($code != $check->code) {
            throw new Exception('验证码不正确');
            }*/

            DB::beginTransaction();

            $res = User::create([
                'account' => getAccount(),
                'nickname' => getNickname(),
                'email' => $email,
                'phone' => $phone,
                'password' => md5($password),
                'pay_pass' => '',
                'headimg' => randomHeadimg(),
                'token' => getToken(),
            ]);
            //处理账号显示（用*替换）
            $showAccount = hideStar($res->account);
            //写入消息
            $msgArr = [
                'msg_id' => 1,
                'uid' => $res->id,
                'message' => [$showAccount],
                'push_message' => [$showAccount],
            ];
            (new Message())->syspublishsmsAll($msgArr);

            //调用云信注册
            $model = new Yunxin\Yunxin();
            $name = $res->nickname;
            $id = $res->id;
            $img = config('alioss.host').'/'.$res->headimg;
            $arr = $model->register_yx($id, $name, $img);
            if ($arr['status'] = 1) {
                $yx_check = User::where('id', $id)->update(['yx_status' => 2]);
            }

            DB::commit();

            $data['uid'] = $res->id;
            $data['account'] = $res->account;
            $data['nickname'] = $res->nickname;
            $data['email'] = $res->email;
            $data['phone'] = $res->phone;
            $data['headimg'] = config('alioss.host').'/'.$res->headimg;
            $data['real_status'] = $res->real_status;

            return response()->json(['status' => 1, 'msg' => '注册成功', 'data' => $data]);
        } catch (Exception $e) {
            //回滚
            DB::rollback();
            //接收错误号
            $msg = $e->getMessage();

            return respF($msg);
        }
    }

    /**
     * 忘记密码
     *
     * @author hxq
     *
     * @param Request $request [description]
     *
     * @return \Illuminate\Http\JsonResponse [type] [description]
     */
    public function forget_password(Request $request)
    {
        $data = [];
        $account = $request->get('account'); //手机号或邮箱
        $password = $request->get('password');
        $code = $request->get('code');
        //验证参数
        if (empty($account) || empty($password) || empty($code)) {
            //参数错误
            return respF(1003);
        }
        //判断是手机还是邮箱
        if (isPhone($account)) {
            //查找用户
            $user = User::where(['phone' => $account])->first();
            //手机验证码
            $check = PhoneSms::where(['phone' => $account, 'type' => 3])
                ->orderBy('created_at', 'desc')->first();
        } elseif (isEmail($account)) {
            //查找用户
            $user = User::where(['email' => $account])->first();
            //邮箱验证码
            $check = EmailSms::where(['email' => $account, 'type' => 3])
                ->orderBy('created_at', 'desc')->first();
        } else {
            //账号格式不正确
            return respF(2011);
        }
        if (!$user) {
            //用户不存在
            return respF(1001);
        }

        //验证密码
        /*if (md5($password) == $user->password) {
        //新密码不能与原密码相同
        return respF(2013);
        }*/
        /*if (!$check) {
        throw new Exception('请获取验证码');
        }
        if ($check->expire_time < time()) {
        throw new Exception('验证码已过期');
        }
        if ($code != $check->code) {
        throw new Exception('验证码不正确');
        }*/

        $user->update([
            'password' => md5($password),
        ]);
        $data['uid'] = $user->id;
        $data['account'] = $user->account;
        $data['nickname'] = $user->nickname;
        $data['email'] = $user->email;
        $data['phone'] = $user->phone;
        $data['headimg'] = config('alioss.host').'/'.$user->headimg;
        $data['real_status'] = $user->real_status;

        return response()->json(['status' => 1, 'msg' => '修改成功', 'data' => $data]);
    }

    /**
     * 设置-修改登录密码
     *
     * @author hxq
     *
     * @param Request $request [description]
     *
     * @return \Illuminate\Http\JsonResponse [type] [description]
     */
    public function update_password(Request $request)
    {
        $uid = $request->get('uid');
        $password = $request->get('password');
        $old_pass = $request->get('old_pass');
        //验证参数
        if (empty($uid) || empty($password) || empty($old_pass)) {
            //参数错误
            return respF(1003);
        }
        //验证密码
        if ($password == $old_pass) {
            //新密码不能与原密码相同
            return respF(2013);
        }
        //查找用户
        $user = User::find($uid);
        //未找到用户
        if (count($user) == 0) {
            //用户不存在
            return respF(1001);
        }
        //验证密码
        if ($user->password != md5($old_pass)) {
            //密码不正确
            return respF(2016);
        }
        //验证新密码
        if ($user->password == md5($password)) {
            //新密码不能与原密码相同
            return respF(2013);
        }
        //不能与交易密码相同
        if ($user->pay_pass == md5($password)) {

            return respF(2018);
        }

        //更新密码
        $user->update([
            'password' => md5($password),
        ]);
        //写入消息
        $msg = ['msg_id' => 3, 'uid' => $uid];
        (new Message())->syspublishsmsAll($msg);

        return response()->json(['status' => 1, 'msg' => '修改成功']);
    }

    /**
     * 设置-修改交易密码
     *
     * @author hxq
     *
     * @param Request $request [description]
     *
     * @return \Illuminate\Http\JsonResponse [type] [description]
     */
    public function update_pay_pass(Request $request)
    {
        $uid = $request->get('uid');
        $password = $request->get('password');
        $old_pass = $request->get('old_pass');
        $pay_pass = $request->get('pay_pass');
        //验证参数
        if (empty($uid) || empty($password) || empty($old_pass) || empty($pay_pass)) {
            //参数错误
            return respF(1003);
        }
        //验证密码
        if ($pay_pass == $old_pass) {
            //新密码不能与原密码相同
            return respF(2013);
        }
        //查找用户
        $user = User::find($uid);
        //未找到用户
        if (!$user) {
            //用户不存在
            return respF(1001);
        }
        //验证登录密码
        if ($user->password != md5($password)) {
            //登录密码不正确
            return respF(2017);
        }
        //验证交易密码
        if ($user->pay_pass != md5($old_pass)) {
            //交易密码错误
            return respF(2026);
        }
        if ($user->password == md5($pay_pass)) {

            return respF(2018);
        }
        //更新密码
        $user->update([
            'pay_pass' => md5($pay_pass),
        ]);
        //写入消息
        $msg = ['msg_id' => 4, 'uid' => $uid];
        (new Message())->syspublishsmsAll($msg);

        return response()->json(['status' => 1, 'msg' => '修改成功']);
    }

    /**
     * 设置修改交易密码通过验证码
     *
     * @author hxq
     *
     * @param Request $request [description]
     *
     * @return \Illuminate\Http\JsonResponse [type] [description]
     */
    public function update_pass_by_code(Request $request)
    {
        $account = $request->get('account');
        $code = $request->get('code');
        $pay_pass = $request->get('pay_pass');
        //验证参数
        if (empty($account) || empty($pay_pass))
            return respF(1003);
        //查找用户
        if (isPhone($account)) {
            //查找用户
            $user = User::where(['phone' => $account])->first();
            //手机验证码
            $check = PhoneSms::where(['phone' => $account, 'type' => 4])->orderBy('created_at', 'desc')->first();
        } elseif (isEmail($account)) {
            //查找用户
            $user = User::where(['email' => $account])->first();
            //邮箱验证码
            $check = EmailSms::where(['email' => $account, 'type' => 4])->orderBy('created_at', 'desc')->first();
        } else {
            //账号格式不正确
            return respF(2011);
        }
        //未找到用户
        if (!$user)
            return respF(1001);//用户不存在
        //验证密码
        if ($user->password == md5($pay_pass))
            return respF(2018);//交易密码不能与登录密码相同
        if ($user->pay_pass == md5($pay_pass))
            return respF(2035);//不能更改为原支付密码  --by zrc 6-2
        if ($code) {
            /*$check = EmailSms::where(['email' => $user->email, 'type' => 4])
            ->orderBy('created_at', 'desc')->first();
            if(count($check) == 0) {
            $check = PhoneSms::where(['phone' => $user->phone, 'type' => 4])
            ->orderBy('created_at', 'desc')->first();
            }
            if (!$check) {
            throw new Exception('请获取验证码');
            }
            if ($check->expire_time < time()) {
            throw new Exception('验证码已过期');
            }
            if ($code != $check->code) {
            throw new Exception('验证码不正确');
            }*/
        }
        //更新密码
        $user->update(['pay_pass' => md5($pay_pass)]);
        //写入消息
        $msg = ['msg_id' => 2, 'uid' => $user->id];
        (new Message())->syspublishsmsAll($msg);
        return response()->json(['status' => 1, 'msg' => '修改成功']);
    }

    /**
     * 第一次设置交易密码(废弃).
     *
     * @param Request $request [description]
     */
    public function set_pay_pass(Request $request)
    {
        $uid = $request->get('uid');
        $pay_pass = $request->get('pay_pass');
        $repass = $request->get('repass');

        if (empty($uid) || empty($pay_pass) || empty($repass)) {
            //缺少参数
            return respF(1003);
        }

        if ($pay_pass != $repass) {
            //两次密码不一致
            return respF(2030);
        }

        $user = User::find($uid);

        if (!$user) {
            //用户不存在
            return respF(1001);
        }

        if ($user->password == md5($pay_pass)) {
            //交易密码不能与登录密码相同
            return respF(2018);
        }

        if (!empty($user->pay_pass)) {
            //交易密码已设置，请去个人中心修改
            return respF(2014);
        }

        $user->update(['pay_pass' => md5($pay_pass)]);

        return response()->json(['status' => 1, 'msg' => '设置成功']);
    }

    public function error(Request $request)
    {
        //dump(1);die;
        return view('api/login/error');
    }

    public function login(Request $request)
    {
        //dump(1);die;
        return view('api/login/login');
    }
}
